use super::WebSearchResult;
use reqwest::Client;
use scraper::{Html, Selector};
use urlencoding::encode;
use anyhow::{Result, Context};

#[allow(unused)]
pub async fn search(query: &str, max_results: usize) -> Result<Vec<WebSearchResult>> {
    let client = Client::new();
    let url = format!(
        "https://www.google.com/search?q={}",
        encode(query)
    );

    let res = client
        .get(&url)
        .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36")
        .send()
        .await
        .context("Send http request")?
        .text()
        .await
        .context("Parse text")?;

    let document = Html::parse_document(&res);
    let selector = Selector::parse("div.g > div > div > a").unwrap();

    let results = document.select(&selector).into_iter().take(max_results)
        .map(|a| {
            let title = a.text().collect::<Vec<_>>().join("").trim().to_string();
            let href = a.value().attr("href").unwrap_or("").to_string();
            WebSearchResult::new(title, href)
        })
        .collect();

    Ok(results)
}

#[allow(unused)]
#[cfg(test)]
mod test {
    use super::*;

    #[tokio::test]
    async fn test_search_rust() {
        match search("Rust", 2).await {
            Ok(results) => {
                for result in results {
                    println!("{}\n", result);
                }
            }
            Err(err) => println!("Search failed!"),
        }
    }
}